/**
 * User: alesj
 * Date: 2004.8.26
 * Time: 9:50:15
 */

package com.generalynx.common.filters;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionFilter implements Filter {

    protected final Log logger = LogFactory.getLog(getClass());
    public static final String CHECKED = "checked";

    protected FilterConfig filterConfig = null;
    protected String session_key = null;
    protected String redirect_url;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.session_key = filterConfig.getInitParameter("session_key");
        this.redirect_url = filterConfig.getInitParameter("redirect_url");
        //info
        logger.info("session_key = " + session_key + " | " + "redirect_url = " + redirect_url);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpSession session = httpServletRequest.getSession();

        if (session.getAttribute(session_key) == null && session.getAttribute(CHECKED) == null) {
            boolean isLogin = httpServletRequest.getRequestURI().indexOf("login") >= 0;
            boolean isMailer = httpServletRequest.getRequestURI().indexOf("mailer") >= 0;

            if (!isLogin && !isMailer) {
                System.out.println("Session inactive, redirecting: " + redirect_url);
                session.setAttribute("checked", Boolean.TRUE);
                request.getRequestDispatcher(redirect_url).forward(request, response);
                return;
            }
        }

        // Pass control on to the next filter
        chain.doFilter(request, response);
    }

    public void destroy() {
        this.session_key = null;
        this.filterConfig = null;
        this.redirect_url = null;
    }

}
